package com.yhh.myUtils;

import java.io.*;

public class Serializations {

    /**
     * 序列化对象到指定路径文件
     * @param outPath 文件路径
     * @param outObj 需要序列化的对象
     * @throws IOException 当I/O发生异常时
     */
    public static void serialize(String outPath, Object outObj) throws IOException {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(outPath))) {
            oos.writeObject(outObj);
            //System.out.println("保存成功");
        }catch (Exception e){
            System.out.println("保存失败");
            e.printStackTrace();
        }
    }

    /**
     * 从文件中逆序列化出对象
     * @param inPath 文件路径
     * @return 你序列化出的对象
     * @throws IOException 当I/O发生异常时
     * @throws ClassNotFoundException 当文件中不存在序列化的对象时
     */
    public static Object deserialize(String inPath) throws IOException, ClassNotFoundException {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(inPath))) {
            return ois.readObject();
        }
    }
}
